import router from "@/router/index";
import {useStore} from "vuex";
import {getToken} from "@/utils/auth";
import {ElMessage} from "element-plus";

/** 免登录白名单 */
const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
    const store = useStore()
    const username = store.state.user.username
    if (getToken()) {
        if (to.path === '/login') {
            next({path: '/'})
        } else {
            if (username) {
                next()
            } else {
                try {
                    await store.dispatch('user/getInfo')
                    next({...to, replace: true})
                } catch (e) {
                    ElMessage.error(e.message || '路由守卫过程发生错误')
                    next(`/login?redirect=${to.path}`)
                }
            }

        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
        }
    }
})